package com.zyz.I_多线程.死锁;

/**
 * @author: vick
 * @Date: 2025/3/24
 * @Description:
 * @version: 1.0
 */
public class DeadLockTest {
    public static void main(String[] args) {
        StringBuilder stringBuilder1 = new StringBuilder();
        StringBuilder stringBuilder2 = new StringBuilder();

        new Thread() {
            @Override
            public void run() {
                synchronized (stringBuilder1) {
                    stringBuilder1.append("a");
                    stringBuilder2.append("1");

                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                    System.out.println("你先放开stringBuilder2");

                    synchronized (stringBuilder2) {
                        stringBuilder1.append("b");
                        stringBuilder2.append("2");

                        System.out.println(stringBuilder1);
                        System.out.println(stringBuilder2);
                    }
                }
            }
        }.start();


        new Thread() {
            @Override
            public void run() {
                synchronized (stringBuilder2) {
                    stringBuilder1.append("c");
                    stringBuilder2.append("3");

                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                    System.out.println("你放开stringBuilder1，我就放开stringBuilder2");
                    synchronized (stringBuilder1) {
                        stringBuilder1.append("d");
                        stringBuilder2.append("4");

                        System.out.println(stringBuilder1);
                        System.out.println(stringBuilder2);
                    }
                }
            }
        }.start();
    }
}
